package com.qf.index;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import com.alibaba.fastjson.JSONObject;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 新版诺模图的学习时间，有一个top期刊论文，为了方便用户查看历年的年、卷、期，特将仅的top期刊的论文给单独整理成一张表，供福磊使用。此程序需要提供：中科院的TOP期刊清单，以及基于科室发文的TOP期刊清单两个txt文件。
 * 运行此程序前，先证实了在NCBI的原始数据中，没有发现相同的一本期刊的名称（ta字段），具有不同的期刊id号（jid字段），故可以不考虑这种的问题。
 * 贾新志 2025.02.18
 */
public class TopArticle {
    public static void main(String[] args) throws SQLException {

        String newDataName = "html.";
        String ncTextTable = newDataName + "nc_text_table_0320";
        String ncTextTopTable = newDataName + "nc_text_table_top_0320";
        readTable(ncTextTable, "id", "ta`,`jid`,`dp", ncTextTopTable);


    }


    public static void readTable(String ncTextTable, String autoId, String field, String ncTextTopTable) throws SQLException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        int onePageNum = 1000;
        Map<String, Integer> topJournalAndJidMap = getTopJournalAndJidMap();
        Db.use().execute("truncate table " + ncTextTopTable);
        String save = "`aidList`,`mhList`,`isList`,`ptList`,`rnList`,`otList`,`laList`,`plList`,`lidList`,`grList`,`siList`,`oidList`,`conList`,`cinList`,`cnList`,`einList`,`gnList`,`iradList`,`efrList`,`gsList`,`pbList`,`uofList`,`uinList`,`rofList`," +
                "`rinList`,`sfmList`,`isbnList`,`rpfList`,`rpiList`,`ecfList`,`eciList`,`crfList`,`criList`,`oriList`,`spinList`,`drinList`,`ddinList`,`rrfList`,`auList`,`phstList`,`stat`,`dp`,`crdt`,`edat`,`ti`,`so`,`jt`,`pst`,`jid`,`lr`,`own`,`mhda`," +
                "`ta`,`pmid`,`vi`,`pg`,`dcom`,`ip`,`sb`,`ab`,`dep`,`oto`,`pmc`,`pmcr`,`ci`,`cois`,`ir`,`fir`,`tt`,`rf`,`mid`,`fps`,`ps`,`oab`,`oabl`,`fed`,`ed`,`bti`,`ctdt`,`cti`,`cp`,`drdt`,`en`,`rriList`";
        int tableMax = Db.use().queryNumber("select max(" + autoId + ") from " + ncTextTable).intValue();
        if (tableMax > 0) {
            Collection<Integer> tableList = new ArrayList<>();
            NumberUtil.appendRange(0, tableMax + onePageNum, onePageNum, tableList);
            tableList.parallelStream().forEach(startId -> {
                try {
                    List<Entity> tableData = Db.use().query("select `" + autoId + "`,`" + field + "` from " + ncTextTable + " where " + autoId + " between " + startId + " and " + (startId + onePageNum - 1));
//                    System.out.println("\033[31;1m" + format.format(new Date()) + " 读表现在开始：" + startId + " 表名：" + ncTextTable + Utils.printMemoryStr() + "\033[0m");
                    for (Entity entry : tableData) {
                        String ta = Utils.getStrField(entry, "ta").toLowerCase().trim();
                        String jid = Utils.getStrField(entry, "jid");
                        String dp = Utils.getStrField(entry, "dp");
                        int id = Utils.getIntField(entry, autoId);
                        if (topJournalAndJidMap.containsKey(ta) && !jid.isEmpty() && dp.length() > 3 && NumberUtil.isInteger(dp.substring(0, 4))) {
                            if (Integer.parseInt(dp.substring(0, 4)) > 2018) {
                                // insert into pm_ut_aid_info_1w (`c1_list`, `rp_list`, `pmId`) SELECT `c1_list`, `rp_list`, 100 from pm_ut_aid_info where id =1;
                                Db.use().execute("insert into " + ncTextTopTable + " (" + save + ",`bao_jid`) select " + save + "," + topJournalAndJidMap.get(ta) + " from " + ncTextTable + " where " + autoId + " = " + id + ";");
                            }
                        }
                    }
                } catch (SQLException e) {
//                    throw new RuntimeException(e);
                }
            });
        }
        topJournalAndJidMap.clear();
    }

    public static Map<String, Integer> getTopJournalAndJidMap() {
        Map<String, Integer> journalAndBaoJidMap = new HashMap<>();
        String zky = "F:\\WorkSpaces\\Data\\src\\main\\resources\\dict\\dept_top_journal_zky.txt";
        List<String> list = FileUtil.readLines(zky, "utf-8");
        // fuDan_肿瘤学_14834_Blood Cancer J
        // STEM_口腔医学_41854_Dent Mater_0.905
        for (String s : list) {
            String[] split = s.split("_");
            if (split.length > 3 && NumberUtil.isInteger(split[2]) && split[3].length() > 2) {
                journalAndBaoJidMap.put(split[3].toLowerCase().trim(), Integer.parseInt(split[2]));
            }
        }
        String article = "F:\\WorkSpaces\\Data\\src\\main\\resources\\dict\\dept_top_journal_article.txt";
        list = FileUtil.readLines(article, "utf-8");
        for (String s : list) {
            String[] split = s.split("_");
            if (split.length > 3 && NumberUtil.isInteger(split[2]) && split[3].length() > 2) {
                journalAndBaoJidMap.put(split[3].toLowerCase().trim(), Integer.parseInt(split[2]));
            }
        }
        return journalAndBaoJidMap;
    }

    public static Map<String, Integer> getZuHeAndJidMap(String jourMergeTable, String autoId, String field) throws SQLException {
        int onePageNum = 1000;
        Map<String, Integer> zuHeAndJidMap = new HashMap<>();
        int tableMax = Db.use().queryNumber("select max(" + autoId + ") from " + jourMergeTable).intValue();
        if (tableMax > 0) {
            Collection<Integer> tableList = new ArrayList<>();
            NumberUtil.appendRange(0, tableMax + onePageNum, onePageNum, tableList);
            for (Integer startId : tableList) {
                List<Entity> tableData = Db.use().query("select `" + autoId + "`,`" + field + "` from " + jourMergeTable + " where " + autoId + " between " + startId + " and " + (startId + onePageNum - 1));
                for (Entity entry : tableData) {
                    String nlmIds = Utils.getStrField(entry, "nc_nlmid_list");
                    String abbr = Utils.getStrField(entry, "nc_nlm_title_abbreviation").replace("\"", "");
                    int jid = Utils.getIntField(entry, autoId);
                    if (nlmIds.contains("\"]") && !abbr.isEmpty()) {
                        List<String> nlmIdList = JSONObject.parseArray(nlmIds, String.class);
                        for (String nlmId : nlmIdList) {
                            if (!nlmId.isEmpty()) {
                                zuHeAndJidMap.put(Institution.re(nlmId + "_" + abbr), jid);
                            }
                        }
                    }
                    String zuHes = Utils.getStrField(entry, "zuhe");
                    if (zuHes.contains("\"]")) {
                        List<String> zuHeList = JSONObject.parseArray(zuHes, String.class);
                        for (String zuHe : zuHeList) {
                            if (zuHe.contains("ISSN")) {
                                zuHeAndJidMap.put(Institution.re(zuHe), jid);
                            }
                        }
                    }
                }
            }
        }
        return zuHeAndJidMap;
    }


}
